package system

import (
	"context"
	"fmt"
	"private-domain-overseas-service/admin/business/api/internal/repository/system"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"time"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SystemVersionEditLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewSystemVersionEditLogic - 新增/修改版本信息
func NewSystemVersionEditLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SystemVersionEditLogic {
	return &SystemVersionEditLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SystemVersionEditLogic) SystemVersionEdit(req *types.SystemVersionUpdateRequest) error {
	// 创建实例
	versionDao := system.NewSystemVersionDao(l.ctx, l.svcCtx)

	// 组装参数
	versionInfo := &ent.HzSystemAppVersion{
		AppPackageName:        req.AppPackageName,
		AppVersion:            req.AppVersion,
		AppVersionTitle:       req.AppVersionTitle,
		AppPlatform:           req.AppPlatform,
		AppForceUpdateType:    req.AppForceUpdateType,
		AppHotUpdateType:      req.AppHotUpdateType,
		AppPublishStatus:      req.AppPublishStatus,
		AppSdkUpdateType:      req.AppSdkUpdateType,
		AppUpdateDownloadURL:  req.AppUpdateDownloadURL,
		AppVersionDescription: req.AppVersionDescription,
		UpdateAt:              time.Now().Unix(),
	}

	// 新增版本信息
	if req.Type == constant.Add {
		versionInfo.CreatedAt = time.Now().Unix()
		if err := versionDao.SystemVersionCreate(versionInfo, nil); err != nil {
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("添加版本信息失败: %v", err))
		}
	}

	// 编辑版本信息
	if req.Type == constant.Edit && req.Id != 0 {
		versionInfo.ID = int(req.Id)
		if err := versionDao.SystemVersionUpdate(versionInfo, nil); err != nil {
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("修改版本信息失败: %v", err))
		}
	}

	return nil
}
